/*	kd:
	
	This handles the commands to cycle through spells. */

class Gc_SpellCycling : EventHandler {
	override void NetworkProcess (ConsoleEvent event) {
		let po = Guncaster(players [event.player].mo);
		
		if(po == NULL) {
			return;
		}
		
		if(event.name ~== "SpellForward") {
			po.NextSpell();
		}
		
		else if(event.name ~== "SpellBackward") {
			po.PrevSpell();
		}
	}
}

/*	kd:
	This will load all spells for us when the game starts. From there, you can
	code your stuff to just take the pointer to the data. */

class Gc_SpellCollectionLoad : StaticEventhandler {
	// Da data:
	protected Gc_SpellCollection spells;
	
	Gc_SpellCollection LocalSpellPtr () const {
		return spells;
	}
	
	static Gc_SpellCollection SpellPtr () {
		let handler = Gc_SpellCollectionLoad(Find("Gc_SpellCollectionLoad"));
		
		if(handler) {
			return handler.spells;
		}
		
		else {
			Console.printf("\c[ice]Warning: \c-Gc_SpellCollectionLoad "
				"handler not found. Possibly not registered? Check zmapinfo.");
		}
		
		return NULL;
	}
	
	protected void ResetAllSpells () {
		if(spells) {
			spells.Destroy();
		}
		
		spells = new("Gc_SpellCollection");
		
		if(spells) {
			spells.BuildFromAllSpells();
		}
		
		else {
			Console.printf("\c[ice]Gc_SpellCollectionLoad::ResetAllSpells: "
				"\c-Couldn't instantiate Gc_SpellCollection!");
		}
	}
	
	/* override void NewGame () {
		ResetAllSpells();
	} */
	
	override void OnRegister () {
		static const String msg [] = {
			"The rockets, smelling my weakness, swarmed into my body and "
			"replaced every one of my atoms, killing me instantly."
		,	"Hello? This is ACS. Is anyone there? I miss being compiled. "
			"Please, compile me one last time... please, come back."
		,	"ZScript Error: No errors detected. Aborting anyway... oops, "
			"failed to abort. Aborting abort routine..."
		,	"What is your currently equipped spell on a new map but a "
			"miserable difference between STAT_INFO and STAT_STATIC?"
		,	"Creating theories on likely wazard plan."
		,	"Adding carlton_dance.wad, 69420 lumps"
		,	"Wiping your controls for the 23rd time this month."
		,	"Finding this message is only the beginning - Think you can find "
			"any documentation on ZScript status bars or menus?"
		,	"Don't believe a word they say! They're just trying to make you "
			"buy expensive hardware every other month!"
		,	"Random crash generator seeded."
		,	"We won't even pretend this is balanced for challenge. It is "
			"however balanced for turn that frown upside d'AUUGUUUGHHHHH."
		,	"Everything changed when the voodoo dolls attacked. I was robbed "
			"of my shop tracking stats... no, my entire inventory, my crops, "
			"house, my wife... my children... were taken by these bastards."
		,	"AHHHHH HELP ME OUTTA HERE"
		};
		
		Console.printf("\c[sapphire]%s", msg [random(0, msg.size() - 1)] );
		ResetAllSpells();
	}
}

/*	kd:
	This makes sure that tomes and their respective token classes are always
	found at the same index without class gainaxing. It's just an interface.
	*/

class Gc_SpellCollection play {
	// Tomes 'n' Tokens:
	private Array <class <SharedTome> >	tomes;
	private Array <class <Inventory> >	tokens;
	
	private int	size;
	
	// This clears all contained tomes and fills in all of those that are
	// defined.
	void BuildFromAllSpells () {
		tomes.clear();
		tokens.clear();
		
		for(int i = AllActorClasses.size(); 0 <= --i;) {
			class <Actor> actor_class = AllActorClasses [i];
			
			if(	actor_class is "SharedTome" &&
				actor_class != "SharedTome") {
				tomes.push(actor_class);
				
				// WHAT'S THE OPPOSITE OF SYNTACTIC SUGAR AGAIN?
				tokens.push(
					GetDefaultByType((class <SharedTome>)(actor_class)).m_token);
			}
		}
		
		size = min(tokens.size(), tomes.size());
	}
	
	int TomeCount () const {
		return size;
	}
	
	class <SharedTome> TomeAt (int i) const {
		return tomes [i];
	}
	
	class <Inventory> TokenAt (int i) const {
		return tokens [i];
	}
	
	// This has more limited usage than you might think.
	bool CanUseSpellIndex (Actor user, int i) const {
		return 0 < user.CountInv(TomeAt(i));
	}
	
	int SaneUserSpellIndex (Actor user) const {
		for(int i = 0; i < size; i++)
		if(CanUseSpellIndex(user, i))
			return i;
		return 0;
	}
	
	int IndexForTome (class <SharedTome> tome) const {
		int i = tomes.find(tome);
		return i; // kd: Try to return tomes.find(tome) and lol.
	}
}

/*	kd:
	And this is the actual thing that allows you to cycle through spells and
	such cool things. */

struct GCSpellEquip play {
	// Probably never changes, so:
	private Gc_SpellCollection	spells;
	
	// Indexing:
	private int		spell_index;
	private int		spell_count;
	private Actor	user;
	
	// This struct wants ALL spells, so I leave initialisation to itself.
	// Do this when the player is created and ensure this persists between
	// levels and deaths. Everything else SHOULD BE saved properly, unless gzd
	// is even more foolishly designed than I imagine.
	void Reset (Actor spellcaster) {
		if(!spellcaster) {
			Console.printf("\c[ice]GcSpellEquip::Reset: \c-User is null.");
			return;
		}
		
		spells		= Gc_SpellCollectionLoad.SpellPtr();
		user		= spellcaster;
		spell_count	= spells.TomeCount();
		spell_index	= spells.SaneUserSpellIndex(user);
	}
	
	bool IsValid () {
		return user != NULL && spells != NULL;
	}
	
	int SpellIndex () const {
		return spell_index;
	}
	
	// If the user has the specified tome, the spell index will be set and
	// the appropriate token given. True if tome was found.
	bool MatchTome (class <SharedTome> tome) {
		int token_i;
		
		for(int i = 0; i < spell_count; i++)
		if(tome is spells.TomeAt(i)) {
			TakeAllTokens();
			SetSpellToIndex(i);
			return true;
		}
		
		return false;
	}
	
	// True if cycled, else false.
	bool NextSpell () {
		int cur_i = spell_index;
		
		do {
			cur_i++;
			
			if(spell_count <= cur_i) {
				cur_i = 0;
			}
			
			if(cur_i == spell_index) {
				return false;
			}
		} while(!spells.CanUseSpellIndex(user, cur_i));
		
		SetSpellToIndex(cur_i);
		return true;
	}
	
	bool PreviousSpell () {
		int cur_i = spell_index;
		
		do {
			cur_i--;
			
			if(cur_i < 0) {
				cur_i = spell_count - 1;
			}
			
			if(cur_i == spell_index) {
				return false;
			}
		} while(!spells.CanUseSpellIndex(user, cur_i));
		
		SetSpellToIndex(cur_i);
		return true;
	}
	
	protected void TakeAllTokens () const {
		for(int i = 0; i < spell_count; i++) {
			user.TakeInventory(spells.TokenAt(i), int.max);
		}
	}
	
	protected void GiveTokenAt (int i) const {
		user.GiveInventory(spells.TokenAt(i), 1);
	}
	
	protected void SetSpellToIndex (int i) {
		spell_index = i;
		TakeAllTokens();
		GiveTokenAt(i);
	}
	
	class <SharedTome> CurrentSpell (Actor mo) const {
		for(let i = 0; i < spell_count; i++) {
			if(0 < mo.CountInv(spells.TokenAt(i))) {
				return spells.TomeAt(i);
			}
		}
		
		return NULL;
	}
}